# -*- coding: utf-8 -*-

"""
@Datetime: 2019/3/31
@Author: Zhang Yafei
"""
import warnings
import numpy as np
import pandas as pd
from pandas.plotting import scatter_matrix
from sklearn import metrics
from sklearn.cluster import DBSCAN
from sklearn.preprocessing import StandardScaler
from matplotlib import pyplot as plt

warnings.filterwarnings("ignore")


def plot(scores):
    """
    画出不同参数模型评估参数轮廓系数折线图
    :return:
    """
    plt.plot(list(range(5,20)), scores)
    plt.xlabel("Number of Clusters Initialized")
    plt.ylabel("Sihouette Score")
    # plt.savefig('dbscan cluster scatter.png')
    plt.show()


if __name__ == '__main__':
    # 1. 读取数据
    beer = pd.read_csv('data.txt', sep=' ')
    # 2. 读取特征X, 并标准化
    X = beer[beer.columns[beer.columns != 'name']]
    # 3. DBscan聚类
    db = DBSCAN(eps=10, min_samples=2).fit(X)
    labels = db.labels_
    print(labels)
    # 4. 将聚类结果处理
    beer['cluster_db'] = labels
    beer.sort_values('cluster_db')
    beer.groupby('cluster_db').mean()

    # 5. 画出两两特征之间的关系
    colors = np.array(['red', 'green', 'blue', 'yellow'])
    scatter_matrix(X, c=colors[beer.cluster_db], figsize=(10, 10), s=100)
    # plt.savefig('output/dbscan_scatter_matrix.png')
    plt.show()

    # 6. 循环验证最优参数, 并作图
    scores = {}
    for eps in range(5, 20):
        labels = DBSCAN(eps=eps, min_samples=2).fit(X).labels_
        score = metrics.silhouette_score(X, labels)
        scores[eps] = score
    print(scores)
    best_eps = sorted(scores.items(), key=lambda x: x[1], reverse=True)[0][0]
    print(best_eps)
    db = DBSCAN(eps=best_eps, min_samples=2).fit(X)
    labels = db.labels_
    print(labels)
    # plot(scores=scores)


